package com.maybach.web.controller.user;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.maybach.common.BizResult;
import com.maybach.common.dto.UserInfoDTO;
import com.maybach.common.enums.BaseConstants;
import com.maybach.common.enums.user.UserStatusEnum;
import com.maybach.common.model.PartnerDO;
import com.maybach.core.ao.PartnerAO;
import com.maybach.core.ao.UserAO;
import com.maybach.core.form.user.UserForm;
import com.maybach.core.form.user.UserQueryForm;
import com.maybach.core.form.user.UserUpdateStatusForm;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.WebUtil;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;

import libs.fastjson.com.alibaba.fastjson.JSON;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;

/**
 * Created by zhaoshuai on 16/1/14.
 */
@Controller
@RequestMapping("/user/")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserAO userAO;

	@Autowired
	private PartnerAO partnerAO;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}

	/**
	 * 添加页面
	 *
	 * @param model
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "add")
	public String add(@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
			ModelMap model) {
		model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
		if (!model.containsAttribute("userForm")) {
			UserForm userForm = new UserForm();
			model.addAttribute(userForm);
		}
		return "user/add";
	}

	/**
	 * 添加user
	 *
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "doAdd", method = RequestMethod.POST)
	public String doAdd(@Valid UserForm userForm, BindingResult bindingResult,
			@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
			RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
		model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
		if (userAO.isAnotherUserExit(userForm.getLoginName(), null)) {
			bindingResult.addError(new FieldError("userForm", "loginName", "登陆名已存在"));
		}

		if (StringUtils.isNotEmpty(userForm.getCertificateCode())) { // 组织机构代码证非空
			PartnerDO partnerDO = partnerAO.getPartnerByCertificateCode(userForm.getCertificateCode());
			if (null == partnerDO) {
				bindingResult.addError(new FieldError("userForm", "certificateCode", "对应的公司不存在"));
			} else {
				userForm.setPartnerId(partnerDO.getId());
			}
		}

		if (null != userForm.getExtNo() && !userForm.getExtNo().matches("^(\\d{4})?$")) {
			bindingResult.addError(new FieldError("userForm", "extNo", "分机号码格式错误"));
		}

		if (bindingResult.hasErrors()) {
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		}
		try {
			Long userId = userAO.addUser(userForm);
			logger.debug("add user userId={}", userId);

		} catch (DuplicateKeyException e) {
			bindingResult.addError(new FieldError("userForm", "extNo", "分机号码已存在"));
			logger.error("Duplicate extNo. UserForm is " + JSON.toJSONString(userForm), e);
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		} catch (Exception e) {
			logger.error("Insert user error. UserForm is " + JSON.toJSONString(userForm), e);
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		}

		return "result";
	}

	/**
	 * 编辑页面
	 *
	 * @param model
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "edit")
	public String edit(@RequestParam(value = "id") Long id,
			@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
		model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
		if (!model.containsAttribute("userForm")) {
			UserForm userForm = userAO.getUserForm(id);
			if (null == userForm) {
				userForm = new UserForm();
			}
			model.addAttribute(userForm);
		}
		return "user/add";
	}

	/**
	 * 添加user
	 *
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "doUpdate", method = RequestMethod.POST)
	public String doUpdate(@Valid UserForm userForm, BindingResult bindingResult,
			@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,
			RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
		model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

		if (userAO.isAnotherUserExit(userForm.getLoginName(), userForm.getId())) {
			bindingResult.addError(new FieldError("userForm", "loginName", "登陆名已存在"));
		}

		if (StringUtils.isNotEmpty(userForm.getCertificateCode())) { // 组织机构代码证非空
			PartnerDO partnerDO = partnerAO.getPartnerByCertificateCode(userForm.getCertificateCode());
			if (null == partnerDO) {
				bindingResult.addError(new FieldError("userForm", "certificateCode", "对应的公司不存在"));
			} else {
				userForm.setPartnerId(partnerDO.getId());
			}
		}

		if (null != userForm.getExtNo() && !userForm.getExtNo().matches("^(\\d{4})?$")) {
			bindingResult.addError(new FieldError("userForm", "extNo", "分机号码格式错误"));
		}

		if (bindingResult.hasErrors()) {
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		}
		try {
			userAO.updateUser(userForm);
			logger.debug("update user userId={}", userForm.getId());
		} catch (DuplicateKeyException e) {
			bindingResult.addError(new FieldError("userForm", "extNo", "分机号码已存在"));
			logger.error("Duplicate extNo. UserForm is " + JSON.toJSONString(userForm), e);
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		} catch (Exception e) {
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		}

		return "result";
	}

	/**
	 * 用户管理页面
	 *
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(@ModelAttribute("userQueryForm") UserQueryForm userQueryForm, BindingResult bindingResult,
			ModelMap model) {
		if (null == userQueryForm) {
			userQueryForm = new UserQueryForm();
		}
		if (!model.containsAttribute("userQueryForm")) {
			model.addAttribute(userQueryForm);
		}
		try {
			if (CollectionUtils.isEmpty(userQueryForm.getStatus())) {
				userQueryForm
						.setStatus(Arrays.asList(UserStatusEnum.normal.getCode(), UserStatusEnum.disable.getCode()));
			}
			PageResult<UserInfoDTO> result = userAO.queryUser(userQueryForm);
			model.addAttribute("pageResult", result);
			return "user/list";

		} catch (Exception e) {
			logger.error("", e);
			return "result";
		}
	}

	/**
	 * 修改用户状态
	 *
	 * @return
	 */
	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "doUpdateStatus.json", method = RequestMethod.POST)
	public BizResult updateStatusAction(@ModelAttribute("form") UserUpdateStatusForm form) {
		return userAO.updateUserStatus(form);
	}

	/**
	 * 获取全部的省份
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryUser.json")
	public BizResult getUserByRole(@ModelAttribute("userQueryForm") UserQueryForm userQueryForm) {
		BizResult result = new BizResult();
		try {
			if (CollectionUtils.isEmpty(userQueryForm.getStatus())) {
				userQueryForm
						.setStatus(Arrays.asList(UserStatusEnum.normal.getCode(), UserStatusEnum.disable.getCode()));
			}
			PageResult<UserInfoDTO> pageResult = userAO.queryUser(userQueryForm);
			result.setResultDate(pageResult);

		} catch (Exception e) {
			logger.error("查询用户失败[query=" + userQueryForm + "]", e);
			result.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
		}
		return result;

	}

	/**
	 * 用户申请页面
	 * 
	 * @param query
	 * @return
	 */
	/*
	 * @RequestMapping(value = "applyList", method = RequestMethod.GET) public
	 * ModelAndView applyListViewAction(@ModelAttribute("query")
	 * UserApplyListQuery query) { ModelAndView mav = new ModelAndView(); try {
	 * if (null != query) { if (query.getPageNumber() < 1) {
	 * query.setPageNumber(1); } } BizResult result =
	 * userAO.queryPaginationUserApplyAO(query); if (null != result && null !=
	 * result.getData()) { mav.setViewName("/user/applyList");
	 * mav.addAllObjects(result.getData()); } else { mav.setView(new
	 * RedirectView("")); } } catch (Exception e) { logger.error(e.getMessage(),
	 * e); mav.setView(new RedirectView("")); } return mav; }
	 * 
	 *//**
		 * 企业资料申请页面
		 * 
		 * @param applyId
		 * @return
		 */
	/*
	 * @RequestMapping(value = "enterpriseApprove/{applyId}", method =
	 * RequestMethod.GET) public ModelAndView
	 * enterpriseApproveViewAction(@PathVariable("applyId") Long applyId) {
	 * ModelAndView mav = new ModelAndView(); try { BizResult result =
	 * userAO.queryEnterpriseApplyAO(applyId); if (null != result && null !=
	 * result.getData()) { mav.setViewName("/user/enterpriseApprove");
	 * mav.addAllObjects(result.getData()); } else { mav.setView(new
	 * RedirectView("")); } } catch (Exception e) { logger.error(e.getMessage(),
	 * e); mav.setView(new RedirectView("")); } return mav; }
	 * 
	 * 
	 * 
	 *//**
		 * 个人资料申请页面
		 * 
		 * @param applyId
		 * @return
		 */

	/*
	 * @RequestMapping(value = "personApprove/{applyId}", method =
	 * RequestMethod.GET) public ModelAndView
	 * personApproveViewAction(@PathVariable("applyId") Long applyId) {
	 * ModelAndView mav = new ModelAndView(); try { BizResult result =
	 * userAO.queryEnterpriseApplyAO(applyId); if (null != result && null !=
	 * result.getData()) { mav.setViewName("/user/personApprove");
	 * mav.addAllObjects(result.getData()); } else { mav.setView(new
	 * RedirectView("")); } } catch (Exception e) { logger.error(e.getMessage(),
	 * e); mav.setView(new RedirectView("")); } return mav; }
	 * 
	 * 
	 *//**
		 * 根据组织机构代码证查询是否存在合作商
		 * 
		 * @param certificateCode
		 * @return
		 *//*
		 * @ResponseBody
		 * 
		 * @RequestMapping(value = "queryuserByCertificateCode.do", method =
		 * RequestMethod.POST) public Map<String, Object>
		 * queryuserByCertificateCodeAction(@RequestParam("certificateCode")
		 * String certificateCode) { return
		 * userAO.queryuserByCertificateCodeAO(certificateCode).getData(); }
		 */

}
